/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-05-11 16:55:03
 * @LastEditTime : 2023-05-24 10:50:57
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Forge\APSModal.jsx
 * @Description  :
 */
import './index.scss'
import { useEffect, useRef, useState, useCallback } from 'react'
import { useBoolean, useRequest } from 'ahooks'
import Draggable from 'react-draggable'
import { Http } from '../Api'
import { message, Form, Spin, Button } from 'antd'
import { project } from '../Data'
import { FormItem } from '../Form/Form'
import { FormList } from './FormList'

const { imageUrl } = project[window.location.hostname]
const { Autodesk, THREE } = window
// const config3d = { extensions: ['ToolbarExtension'] }

export const ApsCenterFormat = data => {
    return {
        center: new THREE.Vector3(data[0], data[1], data[2]).clone(),
        fov: data[3],
        isOrtho: data[4],
        pivot: new THREE.Vector3(data[5], data[6], data[7]).clone(),
        position: new THREE.Vector3(data[8], data[9], data[10]).clone(),
        up: new THREE.Vector3(data[11], data[12], data[13]).clone(),
        worldUp: new THREE.Vector3(data[14], data[15], data[16]).clone(),
    }
}

export const APSModal = ({ scene }) => {
    const APSBox = useRef()

    const [form] = Form.useForm()
    const [messageApi, contextHolder] = message.useMessage()
    const { runAsync: getBimFileOrganizationRelations } = useRequest(Http, { manual: true })
    const { runAsync: getScenesDetails } = useRequest(Http, { manual: true })

    const [loading, { setTrue, setFalse }] = useBoolean(false)
    const [Viewing, setViewing] = useState()
    const [BimFileList, setBimFileList] = useState()

    const getScenesDetailsFunc = useCallback(
        viewing => {
            getScenesDetails({ url: `getScenesDetails`, data: { ScenesUuid: scene.uuid } }).then(res => {
                const { total, list } = res
                if (total !== 0) {
                    const [{ uuid, constitutesUuid, storagePath, longitude, latitude, center }] = list
                    const data = JSON.parse(center)
                    form.setFieldsValue({ uuid, constitutesUuid, longitude, latitude, center: data })
                    viewing.loadModel(storagePath, {}, () => {
                        viewing.setLightPreset(Number(longitude))
                        viewing.setEnvMapBackground(Number(latitude))
                        viewing.autocam.goToView(ApsCenterFormat(data))
                    })
                }
            })
        },
        [getScenesDetails, scene.uuid, form],
    )

    const switchModal = (type, uuid) => {
        switch (type) {
            case 'url':
                Viewing.tearDown()
                Viewing.loadModel(`${imageUrl}${BimFileList.find(v => v.value === uuid).url}`)
                break
            case 'lng':
                Viewing.setLightPreset(Number(uuid))
                break
            case 'lat':
                Viewing.setEnvMapBackground(Number(uuid))
                break
            default:
                break
        }
    }

    // 添加forge明细
    const { run: posScenesDetails } = useRequest(Http, { manual: true, onSuccess: () => MessageOpen(true) })
    // 修改forge明细
    const { run: putScenesDetails } = useRequest(Http, { manual: true, onSuccess: () => MessageOpen() })
    const MessageOpen = e => {
        setFalse()
        messageApi.success(e ? '添加成功' : '修改成功')
    }

    const Submit = e => {
        setTrue()
        e.center = JSON.stringify(e.center)
        const data = {
            ...e,
            isEnabled: 1,
            sortId: 1,
            tableName: BimFileList.find(v => v.value === e.constitutesUuid).bim_FilesName,
            scenesUuid: scene.uuid,
            storagePath: `${imageUrl}${BimFileList.find(v => v.value === e.constitutesUuid).url}`,
        }
        if (data.uuid) putScenesDetails({ url: `putScenesDetails`, data, path: [data.uuid] })
        else posScenesDetails({ url: `posScenesDetails`, data })
    }

    useEffect(() => {
        getBimFileOrganizationRelations({ url: 'getBimFileOrganizationRelations' }).then(res => {
            const { total, list } = res
            if (total === 0) messageApi.info('当前项目没有APS模型!')
            else {
                Autodesk.Viewing.Initializer({ env: 'Local' }, () => {
                    const viewing = new Autodesk.Viewing.GuiViewer3D(APSBox.current)
                    const data = list.map(item => ({ label: item.bim_FilesName, value: item.bimFilesUuid, ...item }))
                    FormList.find(v => v.dataIndex === 'constitutesUuid').valueEnum = data
                    setViewing(viewing)
                    setBimFileList(data)
                    getScenesDetailsFunc(viewing)
                    viewing.start('', {}, () => messageApi.success('APS场景初始化成功!'))
                })
            }
        })
    }, [getBimFileOrganizationRelations, getScenesDetailsFunc, messageApi])

    return (
        <div className="APSModal">
            {contextHolder}
            <div className="forgeBox" ref={APSBox} />
            <div className="formBox">
                <Draggable defaultPosition={{ x: 1152, y: 0 }} bounds={{ top: 0, left: 0, bottom: 400, right: 1152 }}>
                    <div className="formList">
                        <div className="Title">APS模型信息</div>
                        <div className="Form">
                            <Form
                                form={form}
                                className="APSForm"
                                onFinish={Submit}
                                autoComplete="off"
                                labelAlign="right"
                                labelWrap
                                onValuesChange={e => {
                                    const [key] = Object.keys(e)
                                    const [value] = Object.values(e)
                                    if (key === 'constitutesUuid') switchModal('url', value)
                                    if (key === 'longitude') switchModal('lng', value)
                                    if (key === 'latitude') switchModal('lat', value)
                                }}
                            >
                                <Spin spinning={loading}>
                                    <FormItem form={form} PageData={FormList} Viewing={Viewing} />
                                    <div className="FormBtn">
                                        <Button style={{ width: 300 }} type="primary" htmlType="submit">
                                            提交
                                        </Button>
                                    </div>
                                </Spin>
                            </Form>
                        </div>
                    </div>
                </Draggable>
            </div>
        </div>
    )
}
